#-*- test-case-name: fjork.test.test_server -*-
"""
Defines the Fjork Server

"""
from twisted.application import internet, service
from twisted.internet import defer, reactor
from twisted.python import log
from twisted.web import server

from fjork import pool
from fjork import settings
from fjork.web import Root


class FjorkServer(service.MultiService):
    def __init__(self, port):
        self.pool = pool.Pool()
        service.MultiService.__init__(self)
        webServerFactory = server.Site(Root(self.pool))
        webServer = internet.TCPServer(port, webServerFactory)
        webServer.setName("TooBusyBeingAwesome")
        webServer.setServiceParent(self)

    def _cbProcessPoolStarted(self, result):
        log.msg("Fjork is ready for eBusiness")
        service.MultiService.startService(self)        
        return result

    def _ebProcessPoolError(self, failure):
        log.err("failure starting service:", failure)
        return failure

    def startService(self):
        log.msg("starting services:")
        self.pool.setProcesses(settings.POOL)
        d = defer.Deferred()
        d.addCallback(self._cbProcessPoolStarted)
        d.addErrback(self._ebProcessPoolError)
        reactor.callWhenRunning(self.pool.start, d)
        return d

    def stopService(self):
        print "Shutting down pool:"
        self.pool.shutdown()
        print "Shutting down service:"
        return service.MultiService.stopService(self)

    
